import $V from './$V';

export default function dmi(high, low, close, N) {
    let PosDM = $V.init(high.length,0);
    let NegDM = $V.init(high.length,0);
    let TR = $V.init(high.length,0);
    let PosDI = $V.init(high.length,0);
    let NegDI = $V.init(high.length,0);
    let DX = $V.init(high.length,0);
    let ADX = $V.init(high.length,0);
    for(let i = N-1;i < high.length;i++){
        if(high[i] - high[i-1] > 0){
            PosDM[i] = high[i] - high[i-1];
        } else {
            PosDM[i] = 0;
        }
        if(low[i-1] - low[i] > 0){
            NegDM[i] = low[i-1] - low[i];
        } else {
            NegDM[i] = 0;
        }
        if(PosDM[i] > NegDM[i]){
            NegDM[i] = 0;
        } else {
            PosDM[i] = 0;
        }
        TR[i] = $V.max([Math.abs(high[i] - low[i]),Math.abs(high[i] - close[i-1]),Math.abs(low[i] - close[i - 1])]);
        let sum1 = 0, sum2 = 0, sum3 = 0;
        for (let k = i - N + 1; k <= i; k++) {
            sum1 += PosDM[k];
            sum2 += TR[k];
            sum3 += NegDM[k];
        }
        //console.log(sum1, sum2, sum3)
        PosDI[i] = sum1 / sum2 * 100;
        NegDI[i] = sum3/ sum2 * 100;

        DX[i] = Math.abs(PosDI[i] - NegDI[i])/(PosDI[i] + NegDI[i]) * 100;
        ADX[i] = 2/(N + 1) * DX[i] + (1 - 2/(N + 1)) * DX[i - 1];
    }
    return { PosDI, NegDI, ADX };
}
